import showLoading from '@/components/Loading';
import { getQueryParam, MessageTip, QueryParamKeys } from '@amcax/base';
import { omitBy } from 'lodash';
import { SocketEngine } from 'nextcae-base';

const createWsUrlWithCurLo = (uri: string | URL) => {
  // 切换连接环境
  if (process.env.NODE_ENV === 'development') {
    return `wss://${process.env.REACT_APP_NEXT_URL}${uri}`;
  }
  const url = new URL(uri, window.location.href);
  url.protocol = url.protocol.replace('http', 'ws');
  return url;
};
export class BaseSocket {
  static async getEngine() {
    const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);
    const documentVersion = getQueryParam<string>(QueryParamKeys.VERSION);
    const token = localStorage.getItem('NEXT_TOKEN');
    const tokenType = localStorage.getItem('NEXT_TOKEN_TYPE');
    const url = createWsUrlWithCurLo(
      `/ws/v2/shape?k=amcax&authorization=${tokenType} ${token}` +
        `&p=${documentId}${documentVersion ? '&v=' + documentVersion : ''}&pool=${false}`,
    );
    return await SocketEngine.connect(documentId, url);
  }

  async execCmd(
    params,
    showLoad: boolean = true,
    returnFullResponse?: boolean,
  ) {
    const engine = await BaseSocket.getEngine();
    const hide = showLoad ? showLoading() : null;
    try {
      if (!engine) {
        throw new Error('引擎未连接');
      }
      return await engine.execCmd(
        omitBy(params, (v) => v == null),
        returnFullResponse,
      );
    } catch (error: any) {
      const errorCode = error?.code;
      const errorMsg = error?.message ?? '命令执行失败';
      if (errorCode === 401) {
        // token 失效，清理登录状态
        sessionStorage.clear();
        // 跳转到登录页面
        window.location.href = '/login';
      }
      MessageTip.error(errorMsg);
      throw error;
    } finally {
      hide?.();
    }
  }
}
